/*
 * @Author: Jimmy
 * @LastModifiedBy: Jimmy
 * @Date: 2024-12-14 18:26:49
 * @LastEditTime: 2025-02-25 23:44:27
 * @FilePath: /monitor_belt/src/views/setting/basic/index.tsx
 */
import {
  remoteConfigInfo,
  removeConveyorById,
  updateConfigInfo,
} from "@/api/system";
import {
  Button,
  Divider,
  Flex,
  Form,
  Input,
  message,
  Modal,
  Space,
  Spin,
} from "antd";
import { useEffect, useState } from "react";
import { CloseCircleFilled, PlusCircleFilled } from "@ant-design/icons";
import { useStore } from "@/store/conveyor";

const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};

export type TConveyor = {
  conveyor?: string;
  conveyor_id?: number;
};

const BasicInfo = () => {
  const basicConveyor = {
    conveyor: "",
  };
  const { asyncGetConveyorList } = useStore();

  const [form] = Form.useForm();
  const [loading, setLoading] = useState<boolean>(false);
  const [conveyors, setConveyors] = useState<TConveyor[]>([
    { ...basicConveyor },
  ]);

  useEffect(() => {
    searchInfo();
  }, []);

  const searchInfo = async () => {
    setLoading(true);
    try {
      let res = await remoteConfigInfo();
      let { data } = res;
      if (data?.conveyor_info?.length) {
        setConveyors([...data?.conveyor_info]);
      }
      form.setFieldsValue({ ...data });
    } finally {
      setLoading(false);
    }
  };

  const onFinish = () => {
    form.setFieldValue("conveyors", [...conveyors]);
    form
      .validateFields()
      .then(async (values) => {
        setLoading(true);
        try {
          console.log(values);
          let info = { ...values };
          await updateConfigInfo(info);
          asyncGetConveyorList();
          message.success("操作成功");
        } finally {
          setLoading(false);
        }
      })
      .catch((info) => {
        console.log("Validate Failed - ", info);
      });
  };

  const onReset = () => {
    form.resetFields();
    setConveyors([{ ...basicConveyor }]);
  };
  return (
    <Flex
      flex={1}
      justify="center"
      align="center"
      style={{ marginTop: "20px" }}
    >
      <Form
        {...layout}
        form={form}
        name="basic"
        onFinish={onFinish}
        style={{ width: 500 }}
      >
        <Divider>基本配置</Divider>
        <Form.Item label="公司名称" name="company" rules={[{ required: true }]}>
          <Input placeholder="请输入公司名称" />
        </Form.Item>
        <Form.Item label="厂区名称" name="factory" rules={[{ required: true }]}>
          <Input placeholder="请输入厂区名称" />
        </Form.Item>
        {/* <Form.Item label="输送带" name="conveyor" rules={[{ required: true }]}>
          <Input placeholder="请输入输送带" />
        </Form.Item> */}
        <Form.Item label="输送带" name="conveyors" rules={[{ required: true }]}>
          <Flex vertical gap={10}>
            {conveyors.map((conveyor, index: number) => {
              return (
                <Flex align="center" gap={10} key={index}>
                  <Flex flex={1}>
                    <Input
                      value={conveyor.conveyor}
                      onChange={(e) => {
                        let value = e.target.value;
                        conveyors[index].conveyor = value;
                        setConveyors([...conveyors]);
                      }}
                      placeholder="请输入输送带"
                    />
                  </Flex>
                  <Flex>
                    <Button
                      type="link"
                      onClick={() => {
                        setConveyors([...conveyors, { ...basicConveyor }]);
                      }}
                      icon={<PlusCircleFilled style={{ fontSize: "20px" }} />}
                    ></Button>
                    {conveyors.length > 1 && (
                      <Button
                        type="text"
                        onClick={async () => {
                          Modal.confirm({
                            title: "删除提示",
                            content: "确定删除此输送带？",
                            onOk: async () => {
                              try {
                                if (conveyor?.conveyor_id) {
                                  let res:any = await removeConveyorById(
                                    conveyor?.conveyor_id
                                  );
                                  if(res.status=='error'){
                                    Modal.destroyAll()
                                    message.error('输送带有关联设备')
                                    throw new Error("输送带有关联设备");
                                  }
                                }
                                conveyors.splice(index, 1);
                                setConveyors([...conveyors]);
                              }finally {
                              }
                            },
                          });
                        }}
                        danger
                        icon={
                          <CloseCircleFilled style={{ fontSize: "20px" }} />
                        }
                      ></Button>
                    )}
                  </Flex>
                </Flex>
              );
            })}
          </Flex>
        </Form.Item>
        {/* <Form.Item
          label="设备编号"
          name="device_no"
          rules={[{ required: true }]}
        >
          <Input placeholder="请输入设备编号" />
        </Form.Item> */}
        <Form.Item {...tailLayout}>
          <Space>
            <Button htmlType="button" onClick={onReset}>
              重置
            </Button>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
          </Space>
        </Form.Item>
      </Form>
      <Spin spinning={loading} fullscreen />
    </Flex>
  );
};

export default BasicInfo;
